<?php

namespace app\meizhuangapi\model;

use think\Db;
use app\api\model\OrderRefund as OrderRefundnModel;
/**
 * 售后单模型
 * Class OrderRefund
 * @package app\api\model
 */
class OrderRefund extends OrderRefundnModel
{

    /**
     * 售后单状态文字描述
     * @param $value
     * @param $data
     * @return string
     */
    public function getStateTextAttr($value, $data)
    {
        // 已完成
        if ($data['status'] == 20) {
            if($data['is_user_send']){
                $msg='线上流程已完成，之后流程请联系商家客服';
            }else{
                $msg='已同意换货，请尽快填写发货单信息';
            }
            $text = [10 => '退货退款成功', 20 =>$msg ,30=>'退款成功'];
            return $text[$data['type']];
        }
        // 已取消
        if ($data['status'] == 30) {
            return '已取消';
        }
        // 已拒绝
        if ($data['status'] == 10) {
//            return '已拒绝';
            if($data['type'] == 10){
                $ms='已拒绝退货退款';
            }
            if($data['type'] == 20){
                $ms='已拒绝换货';
            }
            if($data['type'] == 30){
                $ms='已拒绝退款';
            }
            return $ms;
        }
        // 进行中
        if ($data['status'] == 0) {
            if ($data['is_agree'] == 0) {
                return '等待审核中';
            }
            if ($data['type'] == 10) {
                return $data['is_user_send'] ? '已发货，待平台确认' : '已同意退货，请及时发货';
            }
            if ($data['type'] == 30) {
                return $data['is_agree'] ? '已审核通过，待退款' : '等待审核中';
            }
        }
        return $value;
    }


    /**
     * 获取用户售后单列表
     */
    public function getList($user_id, $state = -1){
        $state > -1 && $this->where('status', '=', $state);
        return $this->with(['order_master', 'order_goods.image'])
            ->where('user_id', '=', $user_id)
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 用户发货
     * @param $data
     * @return false|int
     */
    public function delivery($data)
    {
        if (
            $this['type']['value'] == 30
            || $this['is_agree']['value'] != 10
            || $this['is_user_send'] != 0
        ) {
            $this->error = '当前售后单不合法，不允许该操作';
            return false;
        }
        if ($data['express_id'] <= 0) {
            $this->error = '请选择物流公司';
            return false;
        }
        if (empty($data['express_no'])) {
            $this->error = '请填写物流单号';
            return false;
        }
        return $this->save([
            'is_user_send' => 1,
            'send_time' => time(),
            'express_id' => (int)$data['express_id'],
            'express_no' => $data['express_no'],
        ]);
    }

    /**
     * 新增售后单记录
     * @param $user
     * @param $goods
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function apply($user, $goods, $data,$orderRefundId)
    {
        $this->startTrans();
        try {
            if($orderRefundId){
                //删除上次售后记录
                Db::name('order_refund')->where(['order_refund_id'=>$orderRefundId])->delete();
            }
            // 新增售后单记录
            $this->isUpdate(false)->save([
                'order_goods_id' => $data['order_goods_id'],
                'order_id' => $goods['order_id'],
                'user_id' => $user['user_id'],
                'type' => $data['type'],
                'apply_desc' => $data['apply_desc'],
                'is_agree' => 0,
                'create_time'=>time(),
                'update_time'=>0,
                'status' => 0,
                'wxapp_id' => self::$wxapp_id,
                'content'=>$data['content']
            ]);
            if($data['type']==20 && !empty($data['addressId'])){
                $detail = UserAddress::detail($user['user_id'], $data['addressId']);
                $region = array_values($detail['region']);
                $address['order_refund_id']=$this['order_refund_id'];
                $address['name']=$detail['name'];
                $address['phone']=$detail['phone'];
                $address['detail']=$detail['detail'];
                $address['wxapp_id']=self::$wxapp_id;
                $address['create_time']=time();
                $this->addAddress($address);
            }
            // 记录凭证图片关系
            if (isset($data['imagesId']) && !empty($data['imagesId'])) {
                $this->saveImages($this['order_refund_id'], $data['imagesId']);
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }
    /*
     * 记录换货收货地址
     */
    private function addAddress($address){
        return Db::name('order_refund_address')->insert($address);
    }

    /**
     * 记录售后单图片
     */
    private function saveImages($order_refund_id, $images){
        $data = [];
        foreach (explode(',', $images) as $image_id) {
            $data[] = [
                'order_refund_id' => $order_refund_id,
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }
        return !empty($data) && (new OrderRefundImage)->saveAll($data);
    }
}